home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Komputer 2010 April
/
PCWorld0410.iso
/
pluginy Firefox
/
14642
/
14642.xpi
/
chrome
/
modules
/
app.js
next >
Wrap
Text File
|
2009-10-10
|
23KB
|
636 lines
/* Copyright 2009, Boomtango.com. All Rights Reserved. */
/* app.js
* Responsible for high level management of components
*/
var EXPORTED_SYMBOLS = ["boomtangoApp"];
Components.utils.import("resource://boomtango/tracker.js");
Components.utils.import("resource://boomtango/storage.js");
var boomtangoApp = {
cc: Components.classes,
ci: Components.interfaces,
_log:null,
newUser: false,
init: function() {
this.tracker = boomtangoTracker;
this.storage = boomtangoStorage;
this._nextID = 1;
this.sessionStart = Date.now();
// create the boomtango directory if it doesn't exist
var dir = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
dir.append("boomtango");
if(!dir.exists() || !dir.isDirectory()){
dir.create(dir.DIRECTORY_TYPE, 0744);
var datadir = dir.clone();
datadir.append("data");
datadir.create(dir.DIRECTORY_TYPE, 0744);
var trackerdir = dir.clone();
trackerdir.append("trackers");
trackerdir.create(trackerdir.DIRECTORY_TYPE, 0744);
}
this.tracker.init(this);
this.storage.init(this);
this.storage.cleanupDB();
this._blacklist = this.storage.getBlacklist(true);
this._externalBlacklist = this.storage.getBlacklist(false);
this.init = function(){};
},
inBlacklist: function(url){
this.log("app::inBlacklist ("+ this._blacklist.length + ", " + url + ")");
var list = this._blacklist;
var len = list.length;
for(var x = 0; x < len; x++){
if(url.match(list[x])){
this.log("matched [" + list[x] + "]");
return true;
}
}
return false;
},
getBlacklist: function(allrecs) {
return allrecs?this._blacklist:this._externalBlacklist;
},
addBlacklistData: function(data, internalOnly){
this.storage.addBlacklistData(data, internalOnly);
this._blacklist.push(data);
if (!internalOnly) {
this._externalBlacklist.push(data);
}
},
deleteBlacklistData: function(address){
this.storage.deleteBlacklistData(address);
this._blacklist.splice(this._blacklist.indexOf(address),1);
this._externalBlacklist.splice(this._externalBlacklist.indexOf(address),1);
this.log("_blacklist length " + this._blacklist.length);
},
deleteAllBlacklist: function() {
this.storage.deleteAllBlacklist();
this._blacklist = [];
this._externalBlacklist = [];
},
openSettings: function(){
var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
ps.alert(null,"Boomtango", "This feature is not implemented yet");
},
openHistory: function(browser){
this.openAndReuseOneTabPerAttribute(
"boomtangoHistory",
"chrome://boomtango/content/history.xul",
browser
);
},
updateThumb: function(id, data){
return this.storage.updateThumb(id, data);
},
getThumb: function(id){
return this.storage.getThumb(id);
},
getThumbID: function(url){
return this.storage.getThumbID(url);
},
ONEDAY: 24 * 60 * 60 * 1000,
refreshRequired: function(thumbTime){
return thumbTime < this.sessionStart;
},
doSerp: function(browser, doc, query){
var addItem = function(id, value){
var item = doc.createElement('input');
item.type = "hidden";
item.id = id;
item.value = value;
doc.body.appendChild(item);
};
if(!this.useSERP){
return;
}
doc = doc.defaultView.top.document;
this.log("app::doSerp");
query = decodeURIComponent(query).replace(/\+/, ' ');
var serp = this.storage.queryTrackerBySERP(query);
var body = doc.body;
if(serp.totalcount && body){
var data = serp.data;
var len = data.length;
addItem("boomtango.title", this.getString('serp.title'));
for(var x = 0; x < len; x++){
addItem(
"boomtango." + x + ".title",
data[x].title
);
addItem(
"boomtango." + x + ".url",
data[x].url
);
}
addItem("boomtango.totalcount", serp.totalcount.toString());
addItem("boomtango.moretitle",this.getString('serp.moreitems', serp.totalcount));
var self = this;
doc.body.addEventListener("click",
function(e){
if(e.target.id == "boomtango.moreitems"){
doc.defaultView.location.href =
"chrome://boomtango/content/history.xul#view=results&type=search&types=web&offset=0&query=" +
encodeURIComponent(query);
e.stopPropagation();
}
},
true
);
var script = doc.createElement('script');
script.src = "http://ext.boomtango.com/serp.js";
doc.body.appendChild(script);
}
},
onTabOpen: function(browser){
browser.setAttribute("boomtangoID",this.createTabID());
var id = browser.getAttribute("boomtangoID");
this.log("app::onTabOpen (" + id + ")");
},
onTabChange: function(browser){
var doc = browser.contentDocument;
var id = browser.getAttribute("boomtangoID");
var url = doc.location.href;
this.log("app::onTabChange ("+ id + ", " + url + ")");
},
onPageLoad: function(id, doc, thumb, referrer){
var url = doc.location.href;
this.log("app::onPageLoad ("+ id + ", " + url + ")");
var thumbid = typeof thumb == "number" ? thumb : this.storage.addThumb(url, thumb);
return this.tracker.onPageLoad(id, doc, thumbid, referrer);
},
onPageUnload: function(id, doc){
var url = doc.location.href;
this.log("app::onPageUnload ("+ id + ", " + url + ")");
return this.tracker.onPageUnload(id, doc);
},
createTabID: function(){
return "boomtango-" + (this._nextID++);
},
getNextID: function(){
if(!this._nextRowID){
this._nextRowID = Date.now();
}
return this._nextRowID++;
},
generateThumb: function(win, canvas){
if(!this.usethumb){
return "";
}
if(!win){
this.log("generate::thumb (nowin)");
return "";
}
var start = Date.now();
var width = 320;
var height = 240;
var winWidth = win.innerWidth - 25;
var winHeight = win.innerHeight;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,width, height);
ctx.save();
ctx.fillStyle = "white";
ctx.fillRect(0,0,width, height);
if(winWidth && winHeight)
ctx.scale(width / winWidth, height / winHeight);
ctx.drawWindow(win, 0,0, winWidth, winHeight, "rgb(0,0,0)");
var r = canvas.toDataURL("image/png", "");
ctx.restore();
this.log("generate::thumb (" + r.length + ", " + (Date.now() - start) +")");
return r;
},
// prefs
_prefs: Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService).
getBranch("extensions.boomtango."),
getBoolPref: function(name, defvalue){
try {
return this._prefs.getBoolPref(name);
}
catch(e){}
return defvalue;
},
getCharPref: function(name, defvalue){
try {
return this._prefs.getCharPref(name);
}
catch(e){}
return defvalue;
},
getIntPref: function(name, defvalue){
try {
return this._prefs.getIntPref(name);
}
catch(e){}
return defvalue;
},
// pref getters and setters
get _debug() { return this.getBoolPref("debug", false);},
set _debug(val) { this._prefs.setBoolPref("debug", val);},
get uselog() { return this.getBoolPref("uselog", true);},
set uselog(val) { this._prefs.setBoolPref("uselog", val);},
get usethumb() { return this.getBoolPref("usethumb", true);},
set usethumb(val) { this._prefs.setBoolPref("usethumb", val);},
get useKeyCombo() { return this.getBoolPref("usekeycombo", true);},
set useKeyCombo(val) { this._prefs.setBoolPref("usekeycombo", val);},
get useSERP() { return this.getBoolPref("useserp", true);},
set useSERP(val) { this._prefs.setBoolPref("useserp", val);},
get confirmDelete() { return this.getBoolPref("confirmdelete", true);},
set confirmDelete(val) { this._prefs.setBoolPref("confirmdelete", val);},
get showdonate() { return this.getBoolPref("showdonate", true);},
set showdonate(val) { this._prefs.setBoolPref("showdonate", val);},
get firsttime() { return this.getBoolPref("firsttime", true);},
set firsttime(val) { this._prefs.setBoolPref("firsttime", val);},
get lastcleanup() { return this.getIntPref("cleanuptime", 0);},
set lastcleanup(val) { this._prefs.setIntPref("cleanuptime", val);},
get lastshutdown() { return this.getIntPref("lastshutdown", 0);},
set lastshutdown(val) { this._prefs.setIntPref("lastshutdown", val);},
get tabChangeTime() { return this.getIntPref("tabchangetime", 0);},
set tabChangeTime(val) { this._prefs.setIntPref("tabchangetime", val);},
get searchItemsPerPage() { return this.getIntPref("searchitemsperpage", 10);},
set searchItemsPerPage(val) { this._prefs.setIntPref("searchitemsperpage", val);},
get glanceItemsPerPage() { return this.getIntPref("categoryitemsperpage", 5);},
set glanceItemsPerPage(val) { this._prefs.setIntPref("categoryitemsperpage", val);},
get historyView() { return this.getCharPref("historyview", 'category');},
set historyView(val) { this._prefs.setCharPref("historyview", val);},
get killBTData() { return this.getBoolPref("killbtdata", false); },
set killBTData(val) { this._prefs.setBoolPref("killbtdata", val);},
get historyDur() { return this.getCharPref("historyduration", 'day');},
set historyDur(val) { this._prefs.setCharPref("historyduration", val);},
get dbversion() {
return this.getIntPref("dbversion", 0);
},
set dbversion(val) { this._prefs.setIntPref("dbversion", val); },
getTrackerEnabled: function(type){
return this.getBoolPref("trackerEnable-" + type, true);
},
setTrackerEnabled: function(type, val){
this._prefs.setBoolPref("trackerEnable-" + type, val);
},
addCustomCategory: function(name, keywords, regex){
var list = this.getCharPref("customcatlist", "");
if(list.length){
list += "&";
}
var id = encodeURIComponent(name);
this._prefs.setCharPref("cat-keywords-"+id, keywords);
this._prefs.setBoolPref("cat-regex-"+id, regex);
list += id;
this._prefs.setCharPref("customcatlist", list);
},
removeCustomCategory: function(name){
var id = encodeURIComponent(name);
var list = this.getCharPref("customcatlist", "");
var a = list.split('&');
var len = a.length;
var txt = "";
for(var x = 0; x < len; x++){
var s = a[x];
if(s != id){
if(txt.length){
txt += "&";
}
txt += s;
}
}
try {
this._prefs.clearUserPref("cat-keywords-"+id);
this._prefs.clearUserPref("cat-regex-"+id);
} catch(e){}
this._prefs.setCharPref("customcatlist", txt);
},
getCustomCategoryList: function(){
var result = [];
var list = this.getCharPref("customcatlist", "");
var a = list.split('&');
var len = a.length;
for(var x = 0; x < len; x++){
var id = a[x];
var name = decodeURIComponent(id);
var keywords = this.getCharPref("cat-keywords-"+id, "");
var regex = this.getBoolPref("cat-regex-"+id, false);
if(name.length && keywords.length){
result.push({
name: name,
keywords: keywords,
regex: regex
});
}
}
return result;
},
generateColor: function(){
var result = "#";
for (var i = 0; i < 3; i++) {
var val = Math.round(100 * Math.random()) ; // [155-255] = lighter colors
var s = val.toString(16);
if(s.length == 1){
result += "0" + s;
} else {
result += s;
}
}
return result;
},
json: Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON),
getTrackerData: function(id){
var s = this.getCharPref("trackerData-" + id, null);
if(s){
return this.json.decode(s);
}
return null;
},
setTrackerData: function(id, data){
if(!data){
this.resetTrackerData(id);
} else {
this._prefs.setCharPref("trackerData-" + id, this.json.encode(data));
}
},
resetTrackerData: function(id){
try {
this._prefs.clearUserPref("trackerData-"+id);
} catch(e){}
},
getTrackerColor: function(id) {
var type = this.tracker.types[id];
var color;
if(type){
color = type.color;
} else {
color = this.generateColor();
}
return this.getCharPref("trackerColor-" + id, color);
},
setTrackerColor: function(id, color){
this._prefs.setCharPref("trackerColor-" + id, color);
},
resetTrackerColor: function(id){
try {
this._prefs.clearUserPref("trackerColor-"+id);
} catch(e){}
},
get guid() {
var id = this.getCharPref("guid", "");
if(id.length == 0){
var s = (9999999 * Math.random()).toString();
id = this.md5("salty snacks are yummy" + s);
this.guid = id;
}
return id;
},
set guid(val) { this.prefs.setCharPref("guid", val);},
get ext_version() {
var rdf = Components.classes["@mozilla.org/rdf/rdf-service;1"].
getService(Components.interfaces.nsIRDFService);
var ds = Components.classes["@mozilla.org/extensions/manager;1"].
getService(Components.interfaces.nsIExtensionManager).datasource;
var us = rdf.GetResource("urn:mozilla:item:ext@boomtango.com");
var ver = rdf.GetResource(
"http://www.mozilla.org/2004/em-rdf#version");
var target = ds.GetTarget(us, ver, true);
return target.QueryInterface(Components.interfaces.nsIRDFLiteral).
Value.toString();
},
// utils
// https://developer.mozilla.org/en/Code_snippets/Tabbed_browser
openAndReuseOneTabPerAttribute: function(attrName, url, tabbrowser) {
var len = tabbrowser.mTabs.length;
for (var i = 0; i < len; i++){
// Get the next tab
var currentTab = tabbrowser.mTabs[i];
// Does this tab contain our custom attribute?
if (currentTab.hasAttribute(attrName)){
if(currentTab.linkedBrowser.contentDocument.location.href.substring(0, url.length) == url) {
// Yes--select and focus it.
tabbrowser.selectedTab = currentTab;
tabbrowser.focus();
return;
} else {
currentTab.removeAttribute(attrName);
}
}
}
// Create tab
var newTab = tabbrowser.addTab(url);
newTab.setAttribute(attrName, "bt");
tabbrowser.selectedTab = newTab;
tabbrowser.focus();
},
reloadTabsWithAttribute: function(attrName) {
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
for (var index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().getBrowser();
index < tabbrowser.mTabs.length;
index++) {
// Get the next tab
var currentTab = tabbrowser.mTabs[index];
this.log("NOT FOUND");
// Does this tab contain our custom attribute?
if (currentTab.hasAttribute(attrName)) {
this.log("RELOAD");
// Yes--reload
tabbrowser.reloadTab(currentTab);
}
}
},
// http://developer.mozilla.org/index.php?title=En/NsICryptoHash&highlight=md5
md5: function(str){
var converter =
Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var result = {};
var data = converter.convertToByteArray(str, result);
var ch = Components.classes["@mozilla.org/security/hash;1"]
.createInstance(Components.interfaces.nsICryptoHash);
ch.init(ch.MD5);
ch.update(data, data.length);
var hash = ch.finish(false);
function toHexString(charCode){
return ("0" + charCode.toString(16)).slice(-2);
}
return [toHexString(hash.charCodeAt(i)) for (i in hash)].join("");
},
getString: function(id, args){
if(!this._stringBundle){
this._stringBundle = Components.classes
["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://boomtango/locale/bt.properties")
}
if (args){
args = Array.prototype.slice.call(arguments, 1);
return this._stringBundle.formatStringFromName(id,
args,args.length);
}
else {
return this._stringBundle.GetStringFromName(id);
}
},
getWebPage: function(url, callback){
var ios = Components.classes
["@mozilla.org/network/io-service;1"].
getService(this.ci.nsIIOService);
var channel;
try {
channel = ios.newChannelFromURI(
ios.newURI(
url,
"UTF-8",
null
)
);
} catch (e) {
callback(600);
return;
}
var streamLoader = Components.classes["@mozilla.org/network/stream-loader;1"]
.createInstance(Components.interfaces.nsIStreamLoader);
var observer = {
onStreamComplete: function(loader, context, status, length, result){
if (Components.isSuccessCode(status)) {
if(status >= 200 && status < 300){
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "utf-8";
callback(0, converter.convertFromByteArray(result, length));
} else {
callback(status);
}
}
}
};
try {
streamLoader.init(observer);
channel.asyncOpen(streamLoader, null);
} catch(e){
callback(601);
return;
}
},
_logOpen: function() {
var file = this.cc['@mozilla.org/file/directory_service;1']
.getService(this.ci.nsIProperties)
.get('ProfD', this.ci.nsIFile);
file.append("boomtango");
file.append("bt.log");
try {
var size = 0;
if(file.isFile()){
size = file.fileSize;
}
if(size > 200 * 1024 ){
file.remove(false);
}
} catch(e) { }
try {
this._log = this.cc["@mozilla.org/network/file-output-stream;1"]
.createInstance(this.ci.nsIFileOutputStream);
this._log.init(file, 0x02 | 0x08 | 0x10, 0664, 0);
} catch (e) {
this._logClose();
}
},
_logClose: function(){
if(!this._log){
return;
}
try {
this._log.close();
} catch(e) {}
this._log = null;
},
showLogFile: function(){
var ios = this.cc["@mozilla.org/network/io-service;1"].
getService(this.ci.nsIIOService);
var file = this.cc['@mozilla.org/file/directory_service;1']
.getService(this.ci.nsIProperties).get('ProfD', this.ci.nsIFile);
file.append("boomtango");
file.append("bt.log");
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
var tabbrowser = mainWindow.getBrowser();
tabbrowser.selectedTab = tabbrowser.addTab(ios.newFileURI(file).spec);
tabbrowser.focus();
},
log: function(s){
if(!this.uselog){
return;
}
var d = new Date();
var str = "BT." + d.toLocaleFormat("%Y.%m.%d.%H.%M.%S") + ": " + s + "\n";
if(!this._log){
this._logOpen();
}
this._log.write(str, str.length)
if(this._debug){
dump(str);
}
},
debug: function(s){
if(this._debug){
if (typeof(s) == 'object') {
return this.debugObject(s);
}
this.log("(DBG) " + s);
}
},
debugObject: function(o){
if(this._debug){
for(var i in o) { this.debug(" " + i + ": " + o[i]); }
}
}
};